package com.lly.bigdata.bgayx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lly.bigdata.bgayx.common.constants.Constants;
import com.lly.bigdata.bgayx.common.constants.em.CommonEnum;
import com.lly.bigdata.bgayx.common.utils.LoginPerUtils;
import com.lly.bigdata.bgayx.common.utils.StringUtils;
import com.lly.bigdata.bgayx.entity.SysMenu;
import com.lly.bigdata.bgayx.entity.SysUser;
import com.lly.bigdata.bgayx.mapper.SysMenuMapper;
import com.lly.bigdata.bgayx.mapper.SysUserMapper;
import com.lly.bigdata.bgayx.service.ISysMenuPinyinService;
import com.lly.bigdata.bgayx.service.ISysMenuService;
import com.lly.bigdata.bgayx.vo.Result;
import com.lly.bigdata.bgayx.vo.SearchModel;
import com.lly.bigdata.bgayx.vo.SysMenuVo;
import com.lly.bigdata.bgayx.vo.ZTreeBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author lly
 * @since 2020-10-21
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    ISysMenuPinyinService sysMenuPinyinService;

    /**
     * 用户模块权限
     *
     * @param username
     * @return
     */
    public Set<String> getUserMenuPermSet(SysUser user) {
        boolean isadmin = Constants.Session_Mge_Adx.equals(user.getUserId().toString());
        List<SysMenu> menus = new ArrayList<>();
        if (isadmin) {
            menus = baseMapper.selectList(null);
        } else {
            menus = this.baseMapper.getUserMenuPermSet(user.getUsername());
        }
        Set<String> perms = new HashSet<String>();
        menus.forEach(v -> {
            if (StringUtils.isNotBlank(v.getPerms())) {
                perms.addAll(Arrays.asList(v.getPerms().split(",")));
            }
        });
        return perms;
    }

    /**
     * 查询分页数据
     *
     * @param searchModel
     * @return
     */
    @Override
    public Result queryPage(SearchModel searchModel) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        LambdaQueryWrapper<SysMenu> lambda = queryWrapper.lambda();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getS_name())) {
            lambda.like(SysMenu::getName, searchModel.getS_name());
        }
        if (StringUtils.isNotBlank(searchModel.getSd1())) {
            lambda.eq(SysMenu::getPid, searchModel.getSd1());
        }
        queryWrapper.orderByAsc("order_num");
        IPage<SysMenu> page = new Page<>(searchModel.getPageNumber(), searchModel.getPageNumber());
        IPage<SysMenu> pages = baseMapper.selectPage(page, queryWrapper);
        Result res = Result.pageOk(pages.getRecords());
        res.setTotal(pages.getTotal());
        res.setPages(res.getPages());
        return res;
    }

    @Override
    public Result queryAll(SearchModel searchModel) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        LambdaQueryWrapper<SysMenu> lambda = queryWrapper.lambda();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getS_name())) {
            lambda.like(SysMenu::getName, searchModel.getS_name());
        }
        if (StringUtils.isNotBlank(searchModel.getSd1())) {
            lambda.eq(SysMenu::getPid, searchModel.getSd1());
        }
        queryWrapper.orderByAsc("order_num");
        //IPage<SysMenu> page = new Page<>(searchModel.getPageNumber(), searchModel.getPageNumber());
        List<SysMenu> pages = baseMapper.selectList(queryWrapper);
        Result res = Result.pageOk(pages);
        res.setTotal((long) pages.size());
        res.setPages(res.getPages());
        return res;
    }

    /**
     * @return java.util.List<com.lly.bigdata.SysMenu>
     * @Author lly
     * @Description 查询子集是存在
     * @Date 2022/1/10 18:18
     * @Param [pid]
     **/
    @Override
    public int selectCountPid(String pid) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.eq("pid", pid);
        int i = baseMapper.selectCount(queryWrapper);
        return i;
    }

    @Override
    public Result queryGdTree(SearchModel searchModel) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper();
        LambdaQueryWrapper<SysMenu> lambda = queryWrapper.lambda();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getS_name())) {
            lambda.like(SysMenu::getName, searchModel.getS_name());
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getNodeid())) {
            lambda.eq(SysMenu::getPid, searchModel.getNodeid());
        } else {
            lambda.eq(SysMenu::getPid, "0");
        }
        queryWrapper.orderByAsc("order_num");
        List<SysMenu> list = baseMapper.selectList(queryWrapper);
        List<SysMenuVo> voJkfwMenus = new ArrayList<SysMenuVo>();
        for (SysMenu sysMenu : list) {
            SysMenuVo vo = new SysMenuVo();
            BeanUtils.copyProperties(sysMenu, vo);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getN_level())) {
                vo.setLevel((Integer.parseInt(searchModel.getN_level()) + 1));
            }
            int i = selectCountPid(sysMenu.getId());
            vo.setLeaf(i == 0);
            voJkfwMenus.add(vo);

        }
        return Result.pageOk(voJkfwMenus);
    }


    /**
     * @Author lly
     * @param: searchModel
     * @Date 2019/8/23 0023
     * @return: com.bigdata.model.Result
     * @Description 查询所有请求
     */
    @Override
    public Result querySearch(SearchModel searchModel) {
        List<SysMenu> list = baseMapper.querySearch(searchModel);
        return Result.pageOk(list);
    }

    @Override
    public List<ZTreeBean> getTreeBeans(HttpServletRequest request, String id, String type) {
        List<ZTreeBean> treeBeans = new ArrayList<ZTreeBean>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByAsc("order_num");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(id)) {
            queryWrapper.eq("pid", id);
        }
        List<SysMenu> menus = baseMapper.selectList(queryWrapper);
        cgZtree(menus, id, type, treeBeans);
        return treeBeans;
    }

    @Override
    public List<ZTreeBean> userHomeTreeBeans(SysUser user, String id, HttpServletRequest request, String type) {
        List<ZTreeBean> treeBeans = new ArrayList<ZTreeBean>();
        List<SysMenu> menus = null;
        if (LoginPerUtils.isUserManager(user.getUserId())) {
            QueryWrapper<SysMenu> queryWrapper = new QueryWrapper();
            queryWrapper.orderByAsc("order_num");
            menus = baseMapper.selectList(queryWrapper);
        } else {
            SearchModel searchModel = new SearchModel();
            searchModel.setSd1(user.getUserId().toString());
            menus = baseMapper.userTreeMenu(searchModel);
        }
        cgZtree(menus, id, type, treeBeans);
        return treeBeans;
    }

    @Override
    @Transactional(readOnly = false)
    public Result addMenu(SysMenu jkfwMenu) {
        jkfwMenu.setId(IdWorker.get32UUID());
        baseMapper.insert(jkfwMenu);
        sysMenuPinyinService.addPinyin(jkfwMenu);
        return Result.ok();
    }

    @Override
    @Transactional(readOnly = false)
    public void updateMenu(SysMenu jkfwMenu) {
        baseMapper.updateById(jkfwMenu);
        sysMenuPinyinService.delMenuid(jkfwMenu.getId());
        sysMenuPinyinService.addPinyin(jkfwMenu);

    }

    @Override
    public Result delMenu(String id) {

        return null;
    }

    private void cgZtree(List<SysMenu> menus, String pid, String type, List<ZTreeBean> treeBeans) {
        Iterator<SysMenu> itr = menus.iterator();
        ZTreeBean tree = null;
        while (itr.hasNext()) {
            SysMenu xk = itr.next();
            if (!org.apache.commons.lang3.StringUtils.isNotBlank(pid)) {
                pid = "0";
            }
            if (xk.getPid().equals(pid)) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(type) && type.equals("menu")) {
                    if (xk.getType().intValue() == CommonEnum.MenuEm.qx.getIdx()) {
                        continue;
                    }
                }
                tree = new ZTreeBean();
                tree.setId(xk.getId());
                tree.setName(xk.getName());
                tree.setTags(xk);
                tree.setStrurl(xk.getUrl());
                tree.setMenus(xk.getType().toString());
                tree.setChildren(getTree(xk, menus, type));
                if (org.apache.commons.lang3.StringUtils.isNotBlank(type) && (type.equals("fuc") || type.equals("menu"))) {
                    tree.setIsParent(true);
                }
                if (tree.getChildren().size() > 0) {
                    tree.setIsParent(true);
                }
                treeBeans.add(tree);
            }
        }
    }

    private List<ZTreeBean> getTree(SysMenu xk, List<SysMenu> list, String type) {
        List<ZTreeBean> treeBeans = new ArrayList<ZTreeBean>();
        Iterator<SysMenu> itr = list.iterator();
        ZTreeBean treeBean = null;
        while (itr.hasNext()) {
            SysMenu xtk = itr.next();
            if (xtk.getPid().equals(xk.getId())) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(type) && type.equals("menu")) {
                    if (xtk.getType().intValue() == CommonEnum.MenuEm.qx.getIdx()) {
                        continue;
                    }
                }
                treeBean = new ZTreeBean();
                treeBean.setId(xtk.getId());
                treeBean.setName(xtk.getName());
                treeBean.setTags(xtk);
                treeBean.setStrurl(xtk.getUrl());
                treeBean.setMenus(xtk.getType().toString());
                treeBean.setChildren(getTree(xtk, list, type));
                if (org.apache.commons.lang3.StringUtils.isNotBlank(type) && (type.equals("fuc") || type.equals("menu"))) {
                    treeBean.setIsParent(true);
                }
                if (treeBean.getChildren().size() > 0) {
                    treeBean.setIsParent(true);
                }
                treeBeans.add(treeBean);
            }
        }
        return treeBeans;
    }
}
